const querystring = require('querystring')
const  { getList , getDelatil , newBlog , updateBlog , delBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = (req) => {
    if (!req.session.username) {
        return Promise.resolve(
            new ErrorModel('尚未登录')
        )
    }
}
const bloghandleRouther = (req, res) => {
    const url = req.url
    const path = url.split("?")[0]
    //req.method请求方式
    const method = req.method
    // req.query = querystring.parse(url.split("?")[1])
    const id = req.query.id 

    //获取博客列表
    if (method === "GET" && path === "/api/blog/list") {
        const author = req.query.author || ""
        const keyword = req.query.keyword || ""
        const result= getList(author, keyword)
        return result
    }
    //博客详情
    if (method === "GET" && path === "/api/blog/delatil") {
        const result = getDelatil(id)
        return result
    }


    //新建博客
    if (method === "POST" && req.path === "/api/blog/new") {
        const loginCheckResult=loginCheck(req,userid)
        if(loginCheckResult){
            return loginCheckResult
        }
          req.body.author=req.session[userid].username
          const result = newBlog(req.body)
          return result.then(data=>{
            return new SuccessModel(data)
          })
    }
    //更新博客

    if (method === "POST" && path === "/api/blog/update") {
      
//           const loginCheckResult = loginCheck(req,userid)
//         if (loginCheckResult) {
//             // 如果有返回值 -- 说明是未登录
//             return loginCheck
//         }
  const result = updateBlog(id,req.body)
    }
    //删除博客
    if (method === "POST" && path === "/api/blog/delete") {
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            // 未登录
            return loginCheck
        }
        // author是当前的登录用户
        const author = req.session.username;
        const result = delBlog(id, author)
    }
}

module.exports = bloghandleRouther